// 全局变量
let treesData = [];
let currentTreeIndex = 0;
let svg, g, zoom;
let width = window.innerWidth - 80;
let height = document.querySelector('.visualization-area').offsetHeight;
let nodeSize = { width: 40, height: 80 };

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    // 设置事件监听器
    document.getElementById('select-file-btn').addEventListener('click', () => {
        document.getElementById('file-input').click();
    });

    document.getElementById('file-input').addEventListener('change', handleFileSelect);
    document.getElementById('export-pdf-btn').addEventListener('click', exportPDF);
    document.getElementById('zoom-in').addEventListener('click', zoomIn);
    document.getElementById('zoom-out').addEventListener('click', zoomOut);
    document.getElementById('reset-zoom').addEventListener('click', resetZoom);

    // 初始化SVG
    initializeSVG();

    // 显示提示信息
    displayMessage('请上传CSV文件以生成家谱');
});


// 初始化SVG
function initializeSVG() {
    const container = document.getElementById('tree-container');
    container.innerHTML = '';

    svg = d3.select('#tree-container')
        .append('svg')
        .attr('width', width)
        .attr('height', height);

    g = svg.append('g');

    // 设置缩放行为
    zoom = d3.zoom()
        .scaleExtent([0.1, 4])
        .on('zoom', (event) => {
            g.attr('transform', event.transform);
        });

    svg.call(zoom);
}

// 处理文件选择
function handleFileSelect(event) {
    const file = event.target.files[0];
    if (!file) return;

    Papa.parse(file, {
        header: true,
        skipEmptyLines: true,
        complete: function(results) {
            processData(results.data);
        }
    });
}

// 处理数据
function processData(data) {
    // 将CSV数据转换为节点数据
    const nodesMap = {};
    data.forEach(person => {
        nodesMap[person.id] = {
            id: person.id,
            name: person.name,
            gender: person.gender,
            father: person.father,
            mother: person.mother,
            alias: person.alias,
            birthdate: person.birthdate,
            birthtime: person.birthtime,
            isdead: person.isdead,
            deathdate: person.deathdate,
            deathtime: person.deathtime,
            birthplace: person.birthplace,
            currentplace: person.currentplace,
            deathplace: person.deathplace,
            memo: person.memo,
            children: [],
            spouses: new Set(),
            spouse: ''
        };
    });

    // 构建层次结构
    data.forEach(person => {
        const node = nodesMap[person.id];
        const father = nodesMap[person.father];
        const mother = nodesMap[person.mother];

        if (person.father && nodesMap[person.father]) {
            nodesMap[person.father].children.push(node);
            if (mother) {
                father.spouses.add(person.mother);
                mother.spouses.add(person.father);
            }
        } else if (person.mother && nodesMap[person.mother]) {
            nodesMap[person.mother].children.push(node);
            if (father) {
                mother.spouses.add(person.father);
                father.spouses.add(person.mother);
            }
        }
    });

    //生成格式化的spouse字段
    data.forEach(person => {
        const node = nodesMap[person.id];

        if (node.spouses && node.spouses.size > 0) {
            const names = [];
            node.spouses.forEach(spouseId => {
                const spouseNode = nodesMap[spouseId];
                if (spouseNode && spouseNode.name) {
                    names.push(spouseNode.name);
                }
            });

            const spouseNames = names.join('/');
            if (node.gender === 'male') {
                node.spouse = `妻 ` + spouseNames;
            } else {
                node.spouse = `夫 ` + spouseNames;
            }
        }

        // 清理临时字段
        delete node.spouses;
    });


    // 找出所有根节点（没有父母的节点）
    const roots = [];
    Object.values(nodesMap).forEach(node => {
        if ((!node.father || !nodesMap[node.father]) &&
            (!node.mother || !nodesMap[node.mother])) {
            roots.push(node);
        }
    });

    // 对每个根节点的子树进行排序
    roots.forEach(root => {
        sortChildren(root);
    });

    treesData = roots;
    createTabs();

    if (treesData.length > 0) {
        currentTreeIndex = 0;
        renderTree(treesData[0]);
    }
}

// 递归排序子女（按年龄或ID）
function sortChildren(node) {
    if (!node.children || node.children.length === 0) return;

    // 这里简化处理，实际应根据birthdate排序
    node.children.sort((a, b) => {
        return a.id.localeCompare(b.id);
    });

    // 对每个子节点递归排序
    node.children.forEach(child => {
        sortChildren(child);
    });
}

// 创建Tab页
function createTabs() {
    const tabButtons = document.getElementById('tab-buttons');
    tabButtons.innerHTML = '';

    treesData.forEach((tree, index) => {
        const button = document.createElement('button');
        button.className = 'tab-btn';
        button.textContent = `家谱 ${index + 1}: ${tree.name}`;
        button.addEventListener('click', () => {
            // 移除所有active类
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            // 添加active类到当前按钮
            button.classList.add('active');
            // 渲染对应的树
            currentTreeIndex = index;
            renderTree(tree);
        });

        if (index === 0) {
            button.classList.add('active');
        }

        tabButtons.appendChild(button);
    });
}

// 渲染树
function renderTree(rootData) {
    // 清除现有内容
    g.selectAll('*').remove();

    // 创建树布局
    const treeLayout = d3.tree()
        .nodeSize([nodeSize.width * 1.5, nodeSize.height * 2])
        .separation((a, b) => (a.parent === b.parent ? 1 : 1.5));

    //  .size([height, width - 200]);

    // 将数据转换为层次结构
    const root = d3.hierarchy(rootData);

    // 生成树节点位置
    treeLayout(root);

    // 创建连线
    const links = g.selectAll('.link')
        .data(root.links())
        .enter()
        .append('path')
        .attr('class', 'link')
        .attr('d', d3.linkVertical()
            .x(d => d.x)
            .y(d => d.y)
        );

    // 创建节点组
    const nodes = g.selectAll('.node')
        .data(root.descendants())
        .enter()
        .append('g')
        .attr('class', d => `node ${d.data.gender}`)
        .attr('transform', d => `translate(${d.x},${d.y})`)
        .on('click', (event, d) => {
            showTooltip(event, d);
        });

    // 为每个节点添加矩形
    nodes.append('rect')
        .attr('width', nodeSize.width)
        .attr('height', nodeSize.height)
        .attr('x', -nodeSize.width / 2)
        .attr('y', -nodeSize.height / 2)
        .style('fill', d => d.data.isdead === 'yes' ? '#ddd' : null); // 设置为null会回退到CSS样式



    // 为每个节点添加文本（名字）
    nodes.append('text')
        //.attr('class', 'node-text')
        .attr('writing-mode', 'tb')
        .attr('glyph-orientation-vertical', '0')
        .attr('text-anchor', 'middle')
        .attr('dominant-baseline', 'central')
        .text(d => d.data.name)
        .style('font-size', '18px');

    // 添加性别符号
    nodes.append('text')
        .attr('x', -14)
        .attr('y', -25)
        .attr('text-anchor', 'middle')
        .text(d => d.data.gender === 'male' ? '♂' : '♀')
        .style('font-size', '14px')
        .style('fill', d => d.data.gender === 'male' ? '#3498db' : '#e74c3c');

    // 添加妻子名字（竖排）
    nodes.append('text')
        .attr('class', 'node-text-wife')
        .attr('writing-mode', 'tb')
        .attr('glyph-orientation-vertical', '0')
        .attr('text-anchor', 'middle')
        .attr('dominant-baseline', 'central')
        .attr('dx', -nodeSize.width / 2 + 50)
        .attr('dy', 0)
        .style('font-size', '14px')
        .text(d => {
            return d.data.spouse;
        });

    // 初始缩放以适应视图
    const bounds = g.node().getBBox();
    const fullWidth = bounds.width;
    const fullHeight = bounds.height;
    const scale = Math.min(width / fullWidth, height / fullHeight) * 0.8;

    const transform = d3.zoomIdentity
        .translate(width / 2 - (bounds.x + bounds.width / 2) * scale, height / 2 - (bounds.y + bounds.height / 2) * scale)
        .scale(scale);

    svg.call(zoom.transform, transform);
}

// 显示工具提示
function showTooltip(event, d) {
    // 先移除所有已存在的 tooltip
    d3.selectAll('.tooltip').remove();

    const tooltip = d3.select('body')
        .append('div')
        .attr('class', 'tooltip')
        .html(`
    <div><strong>姓名:</strong> ${d.data.name}</div>
    <div><strong>性别:</strong> ${d.data.gender === 'male' ? '男' : '女'}</div>
    <div><strong>别名:</strong> ${d.data.alias || '无'}</div>
    <div><strong>当前居所:</strong> ${d.data.currentplace || '未知'}</div>
    <div><strong>出生日期:</strong> ${d.data.birthdate || '未知'}</div>
    <div><strong>出生地点:</strong> ${d.data.birthplace || '未知'}</div>
    
        ${d.data.isdead === 'yes' ? `
        <div><strong>死亡日期:</strong> ${d.data.deathdate || '未知'}</div>
        <div><strong>埋葬地点:</strong> ${d.data.deathplace || '未知'}</div>
    ` : ''}

    <div><strong>备注:</strong> ${d.data.memo || '无'}</div>
    `);

    tooltip
        .style('left', (event.pageX + 30) + 'px')
        .style('top', (event.pageY - 28) + 'px');

    // 点击其他地方移除工具提示
    d3.select('body').on('click', function () {
        tooltip.remove();
    });

    event.stopPropagation();
}


// 缩放功能
function zoomIn() {
    svg.transition().call(zoom.scaleBy, 1.5);
}

function zoomOut() {
    svg.transition().call(zoom.scaleBy, 0.75);
}

function resetZoom() {
    svg.transition().call(zoom.transform, d3.zoomIdentity);
}

// 导出PDF
function exportPDF() {
    const { jsPDF } = window.jspdf;

    html2canvas(document.getElementById('tree-container')).then(canvas => {
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF('l', 'mm', 'a4');
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = pdf.internal.pageSize.getHeight();
        const imgWidth = canvas.width;
        const imgHeight = canvas.height;
        const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight);
        const imgX = (pdfWidth - imgWidth * ratio) / 2;
        const imgY = (pdfHeight - imgHeight * ratio) / 2;

        pdf.addImage(imgData, 'PNG', imgX, imgY, imgWidth * ratio, imgHeight * ratio);
        pdf.save('家谱.pdf');
    });
}

// 显示消息
function displayMessage(message) {
    g.selectAll('*').remove();

    g.append('text')
        .attr('x', width / 2)
        .attr('y', height / 2)
        .attr('text-anchor', 'middle')
        .attr('dy', '0.32em')
        .text(message)
        .style('font-size', '20px')
        .style('fill', '#999');
}

// 窗口大小调整处理
window.addEventListener('resize', function () {
    width = window.innerWidth - 80;
    height = document.querySelector('.visualization-area').offsetHeight;

    if (svg) {
        svg.attr('width', width).attr('height', height);

        if (treesData.length > 0) {
            renderTree(treesData[currentTreeIndex]);
        }
    }
});